#!/usr/bin/env ruby

=begin
Script: ift.ldsize
Version: 1.0
Author: Jean-Jacques Martrès (jjmartres |at| gmail |dot| com)
Description: This script query ldSize OID from the Infortrend MIB (IFT-SNMP-MIB) to get the logical drive size.
License: GPL2

This script is intended for use with Zabbix > 2.0

USAGE:
 as a script:          ift.ldsize [options]
 as an item:           ift.ldsize["-d","IP_ADDRESS","-c","SNMP_COMMUNITY","-i","LD_INDEX","-b","BLOCK_SIZE"]

OPTIONS
    -h, --help                       Display this help message
    -d, --device IP_ADDRESS          Device IP address discovered by Zabbix
    -c, --community SNMP_COMMUNITY   SNMP community used for the device
    -i, --id LD_INDEX                Logical drive index
    -b, --block BLOCK_SIZE           Block size value
=end
require 'rubygems'
require 'optparse'
require 'snmp'

version="0.0.1"

# Howto use it..quiet simple
OPTIONS = {}
mandatory_options=[:deviceip, :community, :id]
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options]"
  opts.separator ""
  opts.separator "Options"
  opts.on("-h", "--help", "Display this help message") do
    puts opts
    exit(-1)
  end
  opts.on('-d', '--device IP_ADDRESS', String, 'Device IP address discovered by Zabbix') { |v| OPTIONS[:deviceip] = v }
  opts.on('-c', '--community SNMP_COMMUNITY',String, 'SNMP community used for the device') { |v| OPTIONS[:community] = v }
  opts.on('-i', '--id LD_INDEX', Integer, 'Logical drive index') { |v| OPTIONS[:id] = v }
  opts.on('-b', '--block BLOCK_SIZE', Integer, 'Block size value') { |v| OPTIONS[:blocksize] = v }
  opts.separator ""
end

# Show usage when no args pass
if ARGV.empty?
  puts optparse
  exit(-1)
end

# Validate that mandatory parameters are specified
begin
  optparse.parse!(ARGV)
  missing = mandatory_options.select{|p| OPTIONS[p].nil? }
  if not missing.empty?
    puts "Missing options: #{missing.join(', ')}"
    puts optparse
    exit(-1)
  end
  rescue OptionParser::ParseError,OptionParser::InvalidArgument,OptionParser::InvalidOption
       puts $!.to_s
       exit(-1)
end

# Query SNMP OID ldSize
oid_value = Array.new

SNMP::Manager.open(:host => OPTIONS[:deviceip], :community => OPTIONS[:community], :version => :SNMPv2c) do |manager|
  response = manager.get(["1.3.6.1.4.1.1714.1.1.2.1.3.#{OPTIONS[:id]}"])
  response.each_varbind do |vb|
   oid_value.push(vb.value.to_s)
  end
end

if oid_value.any?
  if oid_value[0].match('noSuchInstance')
    puts "-- ERROR -- : No such instance !"
  else
    size = oid_value[0].hex * OPTIONS[:blocksize].to_i
    puts size
    exit(-1)
  end
else
  puts "-- ERROR -- : No response receive from #{OPTIONS[:deviceip]} !"
  exit(-1)
end
